from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from app.core.database import get_db
from app.core.security import get_current_active_user
from app.models.user import User
from app.schemas.user import User as UserSchema, UserCreate, UserUpdate, UserProfile
from app.services.user_service import UserService

router = APIRouter()

@router.get("/", response_model=List[UserSchema], summary="获取用户列表")
async def get_users(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回记录数"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户列表
    需要用户管理权限
    """
    # 检查权限
    if not current_user.has_permission("user:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限访问用户列表"
        )
    
    user_service = UserService(db)
    users = user_service.get_multi(
        skip=skip, 
        limit=limit, 
        search=search, 
        is_active=is_active
    )
    
    # 转换为响应模式
    result = []
    for user in users:
        user_data = UserSchema.from_orm(user)
        user_data.roles = [role.name for role in user.roles]
        user_data.permissions = user_service.get_user_permissions(user.id)
        result.append(user_data)
    
    return result

@router.get("/{user_id}", response_model=UserSchema, summary="获取用户详情")
async def get_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取指定用户的详细信息
    """
    # 检查权限：用户只能查看自己的信息，或者有用户管理权限
    if (user_id != current_user.id and 
        not current_user.has_permission("user:read") and 
        not current_user.is_superuser):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限访问该用户信息"
        )
    
    user_service = UserService(db)
    user = user_service.get(user_id)
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 转换为响应模式
    user_data = UserSchema.from_orm(user)
    user_data.roles = [role.name for role in user.roles]
    user_data.permissions = user_service.get_user_permissions(user.id)
    
    return user_data

@router.post("/", response_model=UserProfile, summary="创建用户")
async def create_user(
    user_data: UserCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    创建新用户
    需要用户创建权限
    """
    # 检查权限
    if not current_user.has_permission("user:create") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限创建用户"
        )
    
    user_service = UserService(db)
    
    # 检查用户名是否已存在
    if user_service.get_by_username(user_data.username):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 检查邮箱是否已存在
    if user_service.get_by_email(user_data.email):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="邮箱已被注册"
        )
    
    # 创建用户
    user = user_service.create(user_data)
    return UserProfile.from_orm(user)

@router.put("/{user_id}", response_model=UserProfile, summary="更新用户")
async def update_user(
    user_id: int,
    user_data: UserUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    更新用户信息
    """
    # 检查权限：用户只能更新自己的信息，或者有用户管理权限
    if (user_id != current_user.id and 
        not current_user.has_permission("user:update") and 
        not current_user.is_superuser):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限更新该用户信息"
        )
    
    user_service = UserService(db)
    
    # 检查用户是否存在
    existing_user = user_service.get(user_id)
    if not existing_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 如果更新用户名，检查是否已存在
    if user_data.username and user_data.username != existing_user.username:
        if user_service.get_by_username(user_data.username):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="用户名已存在"
            )
    
    # 如果更新邮箱，检查是否已存在
    if user_data.email and user_data.email != existing_user.email:
        if user_service.get_by_email(user_data.email):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="邮箱已被注册"
            )
    
    # 更新用户
    user = user_service.update(user_id, user_data)
    return UserProfile.from_orm(user)

@router.delete("/{user_id}", summary="删除用户")
async def delete_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    删除用户
    需要用户删除权限
    """
    # 检查权限
    if not current_user.has_permission("user:delete") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限删除用户"
        )
    
    # 不能删除自己
    if user_id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能删除自己的账户"
        )
    
    user_service = UserService(db)
    
    # 检查用户是否存在
    user = user_service.get(user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 删除用户
    success = user_service.delete(user_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除用户失败"
        )
    
    return {"message": "用户删除成功"}

@router.post("/{user_id}/activate", response_model=UserProfile, summary="激活用户")
async def activate_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    激活用户账户
    需要用户管理权限
    """
    # 检查权限
    if not current_user.has_permission("user:update") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限激活用户"
        )
    
    user_service = UserService(db)
    user = user_service.activate(user_id)
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return UserProfile.from_orm(user)

@router.post("/{user_id}/deactivate", response_model=UserProfile, summary="停用用户")
async def deactivate_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    停用用户账户
    需要用户管理权限
    """
    # 检查权限
    if not current_user.has_permission("user:update") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限停用用户"
        )
    
    # 不能停用自己
    if user_id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能停用自己的账户"
        )
    
    user_service = UserService(db)
    user = user_service.deactivate(user_id)
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return UserProfile.from_orm(user)

@router.get("/stats/summary", summary="获取用户统计")
async def get_user_stats(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户统计信息
    """
    # 检查权限
    if not current_user.has_permission("user:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看用户统计"
        )
    
    user_service = UserService(db)
    
    total_users = user_service.count()
    active_users = user_service.count(is_active=True)
    inactive_users = user_service.count(is_active=False)
    
    return {
        "total_users": total_users,
        "active_users": active_users,
        "inactive_users": inactive_users,
        "activation_rate": round((active_users / total_users * 100) if total_users > 0 else 0, 2)
    }